package com.zfei.gfb.controller;


import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.zfei.gfb.api.InboxService;
import com.zfei.gfb.api.StatsService;
import com.zfei.gfb.api.TalkService;
import com.zfei.gfb.api.domain.Page;
import com.zfei.gfb.api.domain.StatsTag;
import com.zfei.gfb.api.domain.StatsValue;
import com.zfei.gfb.api.domain.TalkEvent;
import com.zfei.gfb.bean.Const;
import com.zfei.gfb.bean.HouseResult;
import com.zfei.gfb.bean.Status;
import com.zfei.gfb.bean.StatusException;
import com.zfei.gfb.core.Auth;
import com.zfei.gfb.core.HttpJson;
import com.zfei.gfb.core.LogResult;
import com.zfei.gfb.dao.GfbGreenPlotApplyMapper;
import com.zfei.gfb.dao.GfbGreenPlotMapper;
import com.zfei.gfb.device.AppContext;
import com.zfei.gfb.model.*;
import com.zfei.gfb.query.h5.H5GreenPlotQuery;
import com.zfei.gfb.request.GfbGetRequest;
import com.zfei.gfb.request.h5.GreenPlotClaimRequest;
import com.zfei.gfb.service.GreenPlotServiceImpl;
import com.zfei.gfb.util.Beans;
import com.zfei.gfb.util.Gsons;
import com.zfei.gfb.util.Now;
import com.zfei.gfb.util.TalkUtil;
import com.zfei.gfb.util.gson.Types;
import com.zfei.gfb.vo.GfbGreenPlotListVo;
import com.zfei.gfb.vo.GfbGreenPlotVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fgh
 * @version 1.0
 */

@Api(tags = "H5菜地接口")
@RestController
@RequestMapping("/h5/green_plot")
public class H5GreenPlotController {

    private static final Logger logger = LoggerFactory.getLogger(H5GreenPlotController.class);

    @Resource
    private GfbGreenPlotMapper gfbGreenPlotMapper;

    @Resource
    private GfbGreenPlotApplyMapper gfbGreenPlotApplyMapper;

    @Resource
    private HttpSession httpSession;

    @Resource
    private TalkService talkService;

    @Resource
    private StatsService statsService;

    @Resource
    private InboxService inboxService;

    @Resource
    private GreenPlotServiceImpl greenPlotService;

    @LogResult
    @Auth(type = {Const.VILLAGER, Const.GUEST})
    @HttpJson("/claim")
    @ApiOperation(value = "菜地认领")
    public Object collect(@RequestBody GreenPlotClaimRequest request) {
        greenPlotService.collect(request);
        return null;
    }

    @Auth(type = {Const.VILLAGER, Const.GUEST})
    @LogResult
    @ApiOperation(value = "我认领的菜地")
    @HttpJson("/claim/my")
    @ApiResponses({
            @ApiResponse(code = 200, message = "成功", response = HouseResult.class),
    })
    public Object claimMy(@RequestBody Page query) {
        AppContext context = AppContext.getInstance();
        String identifierId = context.getIdentifierId();

        query.build(Now::millis);

        List<TalkEvent> events = this.talkService.listClain(identifierId, query);
        if (events.size() == 0) {
            return HouseResult.empty();
        }
        List<Integer> greenPlotList = events.stream().map(talkEvent -> Integer.parseInt(talkEvent.getParent())).collect(Collectors.toList());

        List<GfbGreenPlot> greenPlots = gfbGreenPlotMapper.selectByIds(greenPlotList);

        return HouseResult.build(events, greenPlots);
    }

    @ApiOperation(value = "菜地列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbGreenPlotListVo.class),
    })
    @LogResult
    @HttpJson("/list")
    public Object list(@RequestBody H5GreenPlotQuery query) {
        query.build(Now::millis);
        GfbGreenPlotListVo result = new GfbGreenPlotListVo();
        int total = gfbGreenPlotMapper.totalH5(query);
        result.setTotal(total);
        if (total == 0) {
            result.setData(Lists.newArrayList());
            return result;
        }

        List<GfbGreenPlot> records = gfbGreenPlotMapper.listH5(query);

        List<GfbGreenPlotVo> vos = new ArrayList<>();
        for (GfbGreenPlot record : records) {
            GfbGreenPlotVo vo = Beans.copy(record, GfbGreenPlotVo.class);
            List<String> images = Gsons.fromJson(record.getImages(), Types.StringListType);
            vo.setBrowseNum(statsService.get(record.getId().toString(), StatsTag.GREEN_BROWSE_COUNT).getNum());
            vo.setImages(images);
            vos.add(vo);
        }


        result.setData(vos);
        return result;

    }

    //浏览量
    @Auth(type = {Const.VILLAGER, Const.GUEST, Const.COMPANY})
    @ApiOperation(value = "菜地详情")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = GfbGreenPlotVo.class),
    })
    @LogResult
    @HttpJson("/get")
    public Object get(@RequestBody GfbGetRequest request) {
        request.checkGetNull();
        Integer id = request.getId();

        GfbVillager villager = (GfbVillager) httpSession.getAttribute(AppContext.SESSION_H5_VILLAGER);
        GfbGuest guest = (GfbGuest) httpSession.getAttribute(AppContext.SESSION_H5_GUEST);
        GfbCompany company = (GfbCompany) httpSession.getAttribute(AppContext.SESSION_H5_COMPANY);

        GfbGreenPlot record = gfbGreenPlotMapper.selectByPrimaryKey(id);

        GfbGreenPlotVo vo = Beans.copy(record, GfbGreenPlotVo.class);
        List<String> images = Gsons.fromJson(record.getImages(), Types.StringListType);
        vo.setImages(images);

        StatsValue postStats = new StatsValue(record.getId().toString(), StatsTag.GREEN_BROWSE_COUNT, 1);
        statsService.inc(postStats);

        vo.setBrowseNum(statsService.get(record.getId().toString(), StatsTag.GREEN_BROWSE_COUNT).getNum());
        if (company != null) {
            vo.setClainStatus(3);
        } else  {
            AppContext context = AppContext.getInstance();
            String identifierId = context.getIdentifierId();
            TalkEvent claim = this.talkService.getClaim(identifierId, record.getId().toString());
            vo.setClainStatus(claim == null || claim.isDeleted() ? 1 : 2);
        }

        return vo;
    }
}
